package com.googlecode.messwertepi.module;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.googlecode.messwertepi.configuration.Configuration;
import com.pi4j.wiringpi.Serial;
import gnu.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by eike on 19.07.14.
 */
public class SerialPortProvider implements Provider<SerialPort> {

    final private static Logger LOG = LoggerFactory.getLogger(SerialPortProvider.class);

    final private Configuration configuration;

    @Inject
    public SerialPortProvider(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public SerialPort get() {
        String serialPortDevice = configuration.getSerialPortDevice();
        LOG.debug("Initializing Serial Port on device " + serialPortDevice);

        try {
            System.setProperty("gnu.io.rxtx.SerialPorts", serialPortDevice);
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortDevice);

            int timeout = 2000;
            CommPort commPort = portIdentifier.open(this.getClass().getName(), timeout);
            
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(9600,
                    SerialPort.DATABITS_7,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_EVEN);
            serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

            return serialPort;
        } catch (PortInUseException piue) {
            LOG.error("Serial Port already in use", piue);
            throw new RuntimeException("Serial Port already in use", piue);
        } catch (UnsupportedCommOperationException ucoe) {
            LOG.error("Failed to open Serial Port", ucoe);
            throw new RuntimeException("Failed to open Serial Port", ucoe);
        } catch (NoSuchPortException nspe) {
            LOG.error("No such port " + serialPortDevice);
            throw new RuntimeException("Failed to open Serial Port", nspe);
        }
    }
}
